package com.lincoln.bean;

import com.lincoln.entity.user.DbUser;
import com.lincoln.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;

public class BaseSecurityApi extends BaseApi {
    /**
     * 检查是否登录
     */
    public static void checkLogin() throws ApiCodeException {
        try {
            long userId = getUserId();
            if (userId <= 0) {
                throw new ApiCodeException(10005);
            }
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 获取当前请求绑定的用户id,默认返回0
     *
     * @return
     */
    public static long getUserId() {
        try {
            return Long.parseLong((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取当前请求绑定的用户,默认返回null
     *
     * @return
     */
    public static DbUser getUser() {
        UserService userService = (UserService) SpringBeanFactoryUtils.getBeanByClass(UserService.class);
        return userService.findById(getUserId());
    }

    /**
     * 获取当前请求的用户的所有权限
     *
     * @return
     */
    public static Collection<? extends GrantedAuthority> getAuthorities() {
        return getAuthentication().getAuthorities();
    }

    /**
     * 获取当前请求的用户的权限
     *
     * @return
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
